package com;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.Statement;

/**
 * Connection作用  1.获取执行sql对象
 *                  普通执行sql对象
 *                  Statement createStatement()
 *                  预编译sql的执行sql对象：防止sql注入
 *                  PreparedDtatement prepareStatement(sql)
 *                 2.管控事务
 *                 开启事务 connection.setAutoCommit(false);
 *                 提交事务  connection.commit();
 *                 回滚事务  connection.commit();
 *
 */

public class JDBCDemo03_Connection {
   public static void main(String[] args) throws Exception {
        //1.注册驱动
       //可省略 lib\mysql-connector-java-5.1.48.jar!\META-INF\services\java.sql.Driver 下有响应的驱动
      //Class.forName("com.mysql.jdbc.Driver");
       //2.获取连接  
       //String url="jdbc:mysql://127.0.0.1:3306/db01";
       //如果连接的是本机mysql服务器，并且mysql服务默认端口是3306，则url可以简写为：jdbc:mysql:///数据库名称?参数键值对&
       //配置 useSSL=false 参数，禁用安全连接方式，解决
       //警告提示
       String url="jdbc:mysql:///db01?useSSL=false";
       String user="root";
       String password="137867";
       Connection connection = DriverManager.getConnection(url,user,password);
       Statement statement = null;


       try {
           //==========开启事务=========
           connection.setAutoCommit(false);
           //3编写sql
           String sql="update tb01 set number=2000 where id=1";
           //4.执行sql对象
           statement = connection.createStatement();
           //5.执行sql
           int i = statement.executeUpdate(sql);
           //6处理结果
           System.out.println("方法1   "+i);
            int a=2/0;
           //3编写sql
           String sql2="update tb01 set number=2000 where id=2";
           //4.执行sql对象
           Statement statement2 = connection.createStatement();
           //5.执行sql
           int i2 = statement2.executeUpdate(sql2);
           //6处理结果
           System.out.println("方法2   "+i2);
           //========提交事务==============
           connection.commit();
       } catch (SQLException throwables) {
           throwables.printStackTrace();
           //========回滚事务=============
           connection.rollback();

       }

       //7关闭资源
       statement.close();
       connection.close();
    }
}
